package com.itheima.d1_serialize;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

//目标：了解如何序列化多个对象
public class Demo03 {
    public static void main(String[] args) throws Exception {
        //需求：创建多个Teacher对象，然后一次性序列化
        //1.创建Teacher对象
        Teacher tea1 = new Teacher("苍某空", 48);
        Teacher tea2 = new Teacher("天某翼", 46);
        Teacher tea3 = new Teacher("罗某祥", 49);

        //2.创建ArrayList集合，存入Teacher对象
        ArrayList<Teacher> list = new ArrayList<>();
        list.add(tea1);
        list.add(tea2);
        list.add(tea3);

        //3.创建ObjectOutputStream对象，调用writeObject方法进行序列化
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("day10-io&thread\\resources\\obj.txt"));
        oos.writeObject(list);

        //刷新和释放资源
        oos.flush();
        oos.close();

        //4.尝试读取已经存入文件的对象，创建ObjectInputStream进行反序列化操作
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("day10-io&thread\\resources\\obj.txt"));
        list = (ArrayList<Teacher>) ois.readObject();
        System.out.println(list);
    }
}
